package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.entity.UmsAdmin;
import com.shop.feign.FileService;
import com.shop.mapper.UmsAdminMapper;
import com.shop.service.UmsAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author lpx610
 * @since 2023-10-29
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private FileService fileService;

    @Override
    public IPage<UmsAdmin> list(Integer pageNo, Integer pageSize, String username, Integer order) {
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        if (order == 1) {
            queryWrapper.orderByAsc("sort");
        } else {
            queryWrapper.orderByDesc("sort");
        }
        return this.page(new Page<>(pageNo, pageSize), queryWrapper);
    }

    @Override
    public Boolean add(String username, String password, String phone, String email, Integer gender, MultipartFile file) {
        String icon = fileService.upload(file);
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setUsername(username)
                .setPassword(passwordEncoder.encode(password))
                .setPhone(phone)
                .setEmail(email)
                .setGender(gender)
                .setIcon(icon);
        return this.save(umsAdmin);
    }

    @Override
    public Boolean update(String id, String username, String phone, String email, Integer gender, MultipartFile file) {
        UmsAdmin umsAdmin = new UmsAdmin(id);
        umsAdmin.setUsername(username)
                .setPhone(phone)
                .setEmail(email)
                .setGender(gender);
        if (file != null) {
            String icon = fileService.upload(file);
            umsAdmin.setIcon(icon);
        }
        return this.updateById(umsAdmin);
    }

    @Override
    public Boolean delete(String id, Boolean active) {
        return this.updateById(new UmsAdmin(id).setActive(active));
    }
}
